//
//  XDUserCenterController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/2/21.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDUserCenterController.h"
#import "AFHTTPSessionManager+POST.h"
#import "XDUserCenterCell.h"
#import "XDMybankCardViewController.h"
#import "XDChangePasswordController.h"
#import "XDVerifiedViewController.h"
#import "XDLMGestureViewController.h"
@interface XDUserCenterController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) NSArray *userCenterArr;

//是否绑定银行卡
@property (nonatomic, copy) NSString *bindStatusStr;

@property (nonatomic, strong) NSDictionary *bankInfo;

@end

@implementation XDUserCenterController

- (NSArray *)userCenterArr {
    if (_userCenterArr == nil) {
        _userCenterArr = [NSArray array];
    }
    return  _userCenterArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSUserDefaults *df =   [NSUserDefaults standardUserDefaults] ;
    [df removeObjectForKey:@"isChangePass"];
    [df synchronize];
    
    [self loadData];
}

- (void)loadData {
    
    NSDictionary * param = @{@"method":@"getAccountStatus"};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            
            /*
             
             code = 100000;
             message = "\U64cd\U4f5c\U6210\U529f";
             result =     {
             bankInfo =         {
             bankCode = abc;
             bankIconUrl = "http://172.16.20.248:6060/zhrtChinaWeb/biz-assets/bankIcon/small/abc.png";
             bankName = "\U519c\U4e1a\U94f6\U884c";
             bankNumber = 4575;
             bankType = 1;
             };
             bindStatus = Y;
             safePassStatus = Y;
             verifiedStatus = Y;
             };
             type = success;
             }
             
             */
            NSDictionary *dic = responseObject[@"result"];
            
            self.bankInfo = dic[@"bankInfo"];
            
            self.bindStatusStr = dic[@"bindStatus"];
            NSString *bank = [NSString stringWithFormat:@"%@(%@)", responseObject[@"result"][@"bankInfo"][@"bankName"],responseObject[@"result"][@"bankInfo"][@"bankNumber"]];
            
            NSString *bindStatusStr = [dic[@"bindStatus"] isEqualToString:@"Y"] ? bank : @"未绑卡";
            
            NSString *safePassStatusStr = [dic[@"safePassStatus"] isEqualToString:@"Y"] ? @"已设置" : @"未设置";
            
            NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
            
            NSString *gestureStr = [df valueForKey:@"gestureFinalSaveKey"] ? @"已开启" : @"未开启";
            self.userCenterArr = @[
                                   
       @[@[@"我的银行卡",bindStatusStr]],
       @[@[@"交易密码",safePassStatusStr],
        @[@"手势密码",gestureStr]],
        @[@[@" ", @" "]]                     ];
            
            [self.tableView reloadData];
            } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
            
            
        } else {
            
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


- (void)setupUI {
    
    self.title = @"个人中心";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"about"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonClick)];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - 64) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:tableView];
    tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    self.tableView = tableView;
    self.tableView.backgroundColor = kColorRGB(234, 234, 234);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSArray *arr = self.userCenterArr[section];
    return [arr count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.userCenterArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *myID = @"XDUserCenterCell";
    XDUserCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:myID];
    if (cell == nil) {
        
        cell = [[XDUserCenterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myID];
    }

    if (indexPath.section == 2) {
    
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 50)];
        [btn setTitle:@"安全退出" forState:UIControlStateNormal];
        [btn setTitleColor:kColorRGB(187,147,115)forState:UIControlStateNormal];
        btn.enabled = NO;
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        [cell.contentView addSubview: btn];
    } else {
        [cell cellWithTitle:self.userCenterArr [indexPath.section][indexPath.row][0] dateil:self.userCenterArr[indexPath.section][indexPath.row][1] bankImg:self.bankInfo[@"bankIconUrl"] bindStatusStr:self.bindStatusStr index:indexPath] ;
      
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 2) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定要退出吗？" preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSUserDefaults * df = [NSUserDefaults standardUserDefaults];
            if ([df objectForKey:@"token"]) {
                [df removeObjectForKey:@"token"];
            }
            
            if ([df objectForKey:@"uid"]) {
                [df removeObjectForKey:@"uid"];
            }
            if ([df objectForKey:@"gestureFinalSaveKey"]) {
                [df removeObjectForKey:@"gestureFinalSaveKey"];
            }
            [df synchronize];
            [self.tabBarController setSelectedIndex:0];
            [self.navigationController popToRootViewControllerAnimated:YES];
            
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }];
        
        [alert addAction:okAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else if (indexPath.section == 0) {

            XDMybankCardViewController *bankCordChange = [[XDMybankCardViewController alloc] init];
            [self.navigationController pushViewController:bankCordChange animated:YES];

    }else if (indexPath.section == 1 && indexPath.row == 0) {
        NSDictionary * param = @{@"method":@"getAccountStatus"};
        [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
            
            if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                NSDictionary *dic = responseObject[@"result"];
                NSUserDefaults *df =   [NSUserDefaults standardUserDefaults] ;
                [df setObject:@"Y" forKey:@"isChangePass"];
                [df synchronize];
                if ([dic[@"verifiedStatus"] isEqualToString:@"N"]) {
                    XDVerifiedViewController *verified = [[XDVerifiedViewController alloc] init];
                    [self.navigationController pushViewController:verified animated:YES];
                    
                } else {
                    
                    XDChangePasswordController *changePassword = [[XDChangePasswordController alloc] init];
                    [self.navigationController pushViewController:changePassword animated:YES];
                    
                }
                
            } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
                
                
            } else {
                
                
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];

    }else if (indexPath.section == 1 && indexPath.row == 1) {
        
        XDLMGestureViewController *gesture = [[XDLMGestureViewController alloc] init];
        
        [self.navigationController pushViewController:gesture animated:YES];
    
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 2) {
        return 40;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 10)];
    view.backgroundColor = kColorRGB(234, 234, 234);
    return view;
}

- (void)rightBarButtonClick {
    
    
    NSLog(@"关于");
    
}


@end
